<template>
  <div class="app-container">
    <el-container>
     <el-aside width="200px" style="background-color: white;">
    <el-table
      style="border: none;"
      v-if="refreshTable"
      :data="type1List"
      row-key="itemTypeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @row-click="handleCategoryClick" > <!-- 点击分类行触发查询 -->
      <el-table-column  align="center" prop="itemTypeName" />
    </el-table>

      </el-aside>
      <el-main>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['item:item:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['item:item:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['item:item:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['item:item:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="物料/产品" align="center" prop="itemOrProduct" />
      <el-table-column label="所属分类" align="center" prop="itemTypeName" />
      <el-table-column label="是否启用" align="center" prop="enableFlag" width="140px">
          <template #default="scope">
              <el-switch 
                v-model="scope.row.enableFlag" 
                active-value="Y"
                inactive-value="N"
                active-text="是" 
                inactive-text="否"
                @change="handleEnableChange(scope.row)"
              />
            </template>
      </el-table-column>
    
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['item:item:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['item:item:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料产品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="itemRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物料编码" prop="itemCode">
          <el-input v-model="form.itemCode" placeholder="请输入物料编码" :disabled="value1"/>
          <span v-if="autoNumber" style="margin-left: 10px; white-space: nowrap;">
              <el-switch v-model="value1" @change="handleChange" /> 自动生成
            </span>
        </el-form-item>
        <el-form-item label="物料名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="单位" prop="unitOfMeasure">
          <el-select v-model="form.unitOfMeasure" placeholder="请选择单位" >
            <el-option
              v-for="item in unitOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料/产品" prop="itemOrProduct">
          <el-select 
            v-model="form.itemOrProduct" 
            placeholder="请选择物料/产品" 
            style="width: 100%"
          >
            <!-- 固定选项：第一个“物料”，第二个“产品” -->
            <el-option label="物料" value="物料"></el-option>
            <el-option label="产品" value="产品"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="itemTypeName">
          <el-tree-select
            v-model="form.selectedTypeId"
            @change="syncTypeInfo"
            :data="typeOptions"
            :props="{ value: 'itemTypeId', label: 'itemTypeName', children: 'children' }"
            value-key="itemTypeId"
            placeholder="请选择所属分类"
            check-strictly
          />
        </el-form-item>
        <!-- 新增隐藏的ID和编码输入框（用于提交，不显示给用户） -->
        <el-form-item label="物料类型ID" prop="itemTypeId" class="hidden">
          <el-input v-model="form.itemTypeId" />
        </el-form-item>
        <el-form-item label="物料类型编码" prop="itemTypeCode" class="hidden">
          <el-input v-model="form.itemTypeCode" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enableFlag">
  <el-radio-group 
    v-model="form.enableFlag" 
    style="display: flex; gap: 20px;"  
  >
    <!-- 选项1：显示“是”，值为“Y”（对应数据库存储） -->
    <el-radio label="Y">是</el-radio>
    <!-- 选项2：显示“否”，值为“N”（对应数据库存储） -->
    <el-radio label="N">否</el-radio>
  </el-radio-group>
</el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
     </el-main>
      
    </el-container>
  </div>
</template>

<script setup name="Item">
import { listItem, getItem, delItem, addItem, updateItem,addMaterial } from "@/api/item/item"

import { formatTime } from '@/utils/format';
import { listMeasure } from "@/api/measure/measure"
/** 查询单位列表 */
function getList3() {
  loading.value = true
  listMeasure(unitQueryParams.value).then(response => {
    unitOptions.value = response.rows.map(item => ({
      label: item.measureName, // 下拉框显示的单位名称
      value: item.measureName    // 选中后提交的单位ID（若后端需要名称，这里改为item.measureName）
    }));
    
  }).catch(error => {
    console.error("获取单位列表失败：", error);
    proxy.$modal.msgError("获取单位数据失败，请重试");
  }).finally(() => {
    loading.value = false;
  });
}
//工单编码自动生成
import { ref } from 'vue'
const value1 = ref(false)
function handleChange(value) {
  if (value) {
    form.value.itemCode = 'WL_' + new Date().getTime()
  } else {
    form.value.itemCode = ''
  }
}
import { ElMessage, ElMessageBox } from 'element-plus'
import {updateItem1} from '@/api/item/item'
//是否启用开关
const handleEnableChange = async (row) => {
//console.log(row);

  try {
    await ElMessageBox.confirm(
      `你确认要${row.enableFlag === 'N' ? '冻结' : '启用'}‘${row.itemName}’吗?`,
      '系统提示',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    );
    // 用户确认后执行更新修改是否启用数据
    const response = await updateItem1(row);
    //console.log(response)
    if (response.code=200) {
      ElMessage.success("操作成功");
      getList()
    } else {
      ElMessage.error("操作失败");
      getList()
    }
  } catch (error) {
console.log(error);

    // 捕获取消操作异常，恢复原始状态
    if (error.name === 'CanceledError'|| error.message === 'cancel' || error === 'cancel') {
      getList()
    } else {
      ElMessage.error("操作出错，请重试");
      getList()

    }
  }
}

const { proxy } = getCurrentInstance()
const autoNumber = ref(true)//自动生成工单编号按钮是否显示
const unitOptions = ref([])
const itemList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemCode: null,
    itemName: null,
    itemTypeName: null,
    itemTypeCode: null,    // 新增：物料类型编码（提交用）
    selectedTypeId: null,   // 新增：临时存储树组件选中的ID
     itemTypeId: 1,  // 新增：用于存储选中的物料分类ID
  },
  unitQueryParams: {
    pageNum: 1,
    pageSize: 100,
    measureCode: null,
    measureName: null,
  },
  rules: {
    itemCode: [
      { required: true, message: "物料编码不能为空", trigger: "blur" }
    ],
    itemName: [
      { required: true, message: "物料名称不能为空", trigger: "blur" }
    ],
    unitOfMeasure: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    itemTypeName: [
      { required: true, message: "产品物料类型名称不能为空", trigger: "blur" }
    ],
    parentTypeId: [
      { required: true, message: "父类型ID不能为空", trigger: "blur" }
    ],
    ancestors: [
      { required: true, message: "所有层级父节点不能为空", trigger: "blur" }
    ],
    itemOrProduct: [
      { required: true, message: "产品/物料不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "是否启用不能为空", trigger: "change" }
    ],
  }
})

const {unitQueryParams, queryParams, form, rules } = toRefs(data)

/** 查询物料产品管理列表 */
function getList() {
  loading.value = true
  listItem(queryParams.value).then(response => {
    itemList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    itemOrProduct: null,
    itemTypeId: null,
    itemTypeCode: null,
    itemTypeName: null,
    selectedTypeId: null, // 新增：临时存储选中的分类ID（不提交）
    enableFlag: null,
    safeStockFlag: null,
    minStock: null,
    maxStock: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
     itemTypeId: 1,
  }
  proxy.resetForm("itemRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
    // 清除分类ID查询条件
  queryParams.value.itemTypeId = 1
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itemId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getList3()
  getTreeselect()
  open.value = true
  title.value = "添加物料产品管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   getList3();
  getTreeselect();
  const _itemId = row?.itemId || ids.value;
  getItem(_itemId).then(response => {
    const itemData = response.data;
    form.value = {
      ...itemData,
      selectedTypeId: itemData.itemTypeId  // 关键：用ID回显树组件选中状态
    };
    open.value = true;
    title.value = "修改物料产品管理";
  });
}
const formMaterial=ref({})
/** 提交按钮 */
async function submitForm() {
  formMaterial.value.itemTypeId=form.value.itemTypeId
  formMaterial.value.itemCode=form.value.itemCode
  formMaterial.value.itemName=form.value.itemName
  formMaterial.value.specification=form.value.specification
  formMaterial.value.unitOfMeasure=form.value.unitOfMeasure
  console.log(form.value)
  proxy.$refs["itemRef"].validate(valid => {
    if (valid) {
      if (form.value.itemId != null) {
        updateItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addItem(form.value).then(response => {
          if(response.code==200){
            formMaterial.value.itemId=response.data
            addMaterial(formMaterial.value).then(res=>{
          })//新增库存量
          }
          
          
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
import { delItem1 } from "@/api/stock/stock"
/** 删除按钮操作 */
function handleDelete(row) {
  console.log("删除");
  
  console.log(row.itemId
);
  const _itemIds = row.itemId || ids.value
  proxy.$modal.confirm('是否确认删除物料产品管理编号为"' + _itemIds + '"的数据项？').then(function() {
    return delItem(_itemIds)
  }).then(() => {
    //删除库存现有量数据
    delItem1(row.itemId).then(res=>{
      console.log(res);
      
    })
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('item/item/export', {
    ...queryParams.value
  }, `item_${new Date().getTime()}.xlsx`)
}

getList()


//下拉表
import { listType1} from "@/api/type1/type1"
import { listType} from "@/api/type/type"
/** 新增：处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  queryParams.value.pageNum = 1
  // 执行查询
  getList()
}

const typeOptions = ref([])
const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)


const data1 = reactive({
  queryParams1: {
  },
})

/**
 * 根据选中的分类ID，同步对应的类型名称到form.itemTypeName
 * @param {Number/String} selectedId - 选中的分类ID（from form.selectedTypeId）
 */
function syncTypeInfo(selectedId) {
  // 递归查找选中的分类节点
  const findTypeNode = (treeData) => {
    for (const node of treeData) {
      if (node.itemTypeId === selectedId) return node;
      if (node.children && node.children.length > 0) {
        const childNode = findTypeNode(node.children);
        if (childNode) return childNode;
      }
    }
    return null;
  };

  // 从分类树数据中获取节点信息
  const typeNode = findTypeNode(typeOptions.value[0]?.children || []);
  
  if (typeNode) {
    // 同步三个字段到表单
    form.value.itemTypeId = typeNode.itemTypeId;
    form.value.itemTypeCode = typeNode.itemTypeCode;
    form.value.itemTypeName = typeNode.itemTypeName;
  } else {
    // 未找到时清空
    form.value.itemTypeId = null;
    form.value.itemTypeCode = null;
    form.value.itemTypeName = null;
  }
}

const { queryParams1 } = toRefs(data1)
/** 查询物料分类下拉树结构 */
function getTreeselect() {
  listType().then(response => {
    typeOptions.value = []
    const data = { itemTypeId: 0, itemTypeName: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    typeOptions.value.push(data)
  })
}
/** 查询物料分类列表 */
function getList1() {
  loading.value = true
  listType1(queryParams1.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}
	
	
getList1()
</script>
<style scoped> 
/* 隐藏表单项：不显示、不占位 */
.hidden {
  display: none !important; /* !important 确保样式优先级，避免被覆盖 */
}
</style>